<template>
  <div style="width: 100%;height: 100%">
    <div class="no-data">现对{{ orderNolist.length }}笔订单进行打印~</div>

    <div class="addren-main">
      <div class="list-itme" v-show="fajianrenFlag"><span>发件人</span>
        <picker
          mode="selector"
          @change="bindfajianrenchange"
          v-model="fajianrenIndex"
          :range="fajianrenNameList"
          style="width: 75%;float: right"
        >
          <div
            class="placeholder"
            style="float: left;width: 90%"
          >
            {{ fajianrenName }}
          </div>
          <div
            class="add-ren-ft"
            style="right: 2px;top: 15px;position: relative;"
          >
          </div>
        </picker>
      </div>
      <div class="list-itme" ><span>打印机</span>
        <div v-if="dayinjiList.length <= 0" style="width: 75%;float: right">
          <div
            class="placeholder" @click="shezhidayin"
            style="float: left;width: 90%;color: #0077ff"
          >
            设置打印机
          </div>
          <div
            class="add-ren-ft"
            style="right: 2px;top: 15px;position: relative;"
          >
          </div>
        </div>

        <picker v-if="dayinjiList.length > 0"
                mode="selector"
                @change="bindDayinjichange"
                v-model="dayinjiIndex"
                :range="dayinjiNameList"
                style="width: 75%;float: right"
        >
          <div
            class="placeholder"
            style="float: left;width: 90%"
          >
            {{ dayinjiName }}
          </div>
          <div
            class="add-ren-ft"
            style="right: 2px;top: 15px;position: relative;"
          >
          </div>
        </picker>
      </div>
      <div class="list-itme"><span>电子面单</span>
        <div v-if="miandanList.length <= 0" style="width: 75%;float: right">
          <div
            class="placeholder" @click="shezhimidandan"
            style="float: left;width: 90%;color: #0077ff"
          >
            设置电子面单
          </div>
          <div
            class="add-ren-ft"
            style="right: 2px;top: 15px;position: relative;"
          >
          </div>
        </div>
        <picker v-if="miandanList.length > 0"
                mode="selector"
                @change="bindMiandanchange"
                v-model="miandanIndex"
                :range="miandanNameList"
                style="width: 75%;float: right"
        >
          <div
            class="placeholder"
            style="float: left;width: 90%"
          >
            {{ miandanName }}
          </div>
          <div
            class="add-ren-ft"
            style="right: 2px;top: 15px;position: relative;"
          >
          </div>
        </picker>
      </div>
    </div>
    <div
      class="addren-foot"
      @click="printOrder"
    >
      打印快递单
    </div>
    <mytoast ref="mytoast"/>
    <div class="printInfoDialog" v-if="dayinflag">
      <div class="tankuang-main">
        <div class="title" v-if="fahuozhong">已打印{{ dangqianfahuo }}单/共{{ orderNolist.length }}单</div>
        <div class="title" v-if="fahuowancheng">打印成功{{ chenggongshu }}单，失败<span
          style="color: red">{{ orderNolist.length - chenggongshu }}</span>单
        </div>
        <div class="content" v-if="fahuozhong">
          <div>正在打印，<span style="color: red">请勿刷新页面</span></div>
        </div>
        <div class="content" v-if="fahuowancheng" style="overflow-y:auto;max-height: 300px">
          <div v-for="(fahuo, index) in fahuoList" :key="index">
            <p>{{ fahuo.orderNo }}:{{ fahuo.msg ? fahuo.msg : '打印机连接异常' }}</p>
          </div>
        </div>
        <div class="tankuang-caozuo" v-if="fahuowancheng" @click="doConfirm">
          <a class="confirm" >确定</a>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
    import api from "@/utils/api";
    import mytoast from "@/components/toast";
    import printInfoDialogs from "@/components/printInfoDialog";
    import check from "@/utils/check";

    export default {
        components: {mytoast, printInfoDialogs},

        data() {
            return {
                orderNolist: [],
                fajianrenFlag : false, //默认都选择了发件人

                fajianrenIndex: "",
                fajianrenList: [],
                fajianrenNameList: [],
                fajianrenName: "请选择",

                dayinjiIndex: "",
                dayinjiList: [],
                dayinjiNameList: [],
                dayinjiName: "请选择",

                miandanIndex: "",
                miandanList: [],
                miandanNameList: [],
                miandanName: "请选择",


                dayinflag: false,
                fahuozhong: false,
                dangqianfahuo: '0',

                fahuowancheng: true,
                chenggongshu: '0',
                shibaishu: '0',
                fahuoList: [],

                msg: '',
                deviceId: '4CF48A47-0875-5C98-13A7-DE8733EED2DC'
            };
        },

        onLoad: function (options) {
            this.fajianrenFlag = false;
            this.orderNolist = [];
            if(options.orderNolist){
                var orderList = JSON.parse(options.orderNolist);
                this.orderNolist = [];
                for(var i in orderList){
                    this.orderNolist.push(orderList[i].orderNo);
                    if(orderList[i].isSelectShipper == '0'){ //有订单没选择发件人
                        this.fajianrenFlag = true;
                    }
                }
            }
        },

        onShow() {
            this.fajianrenIndex = "";
            this.fajianrenList = [];
            this.fajianrenNameList = [];
            this.fajianrenName = "请选择";

            this.dayinjiIndex = "";
            this.dayinjiList = [];
            this.dayinjiNameList = [];
            this.dayinjiName = "请选择";

            this.miandanIndex = "";
            this.miandanList = [];
            this.miandanNameList = [];
            this.miandanName = "请选择";
            this.doConfirm();
            this.loadData();
        },

        created() {
        },

        methods: {
            doConfirm() {
                this.dayinflag = false;
                this.fahuoList = [];
                this.fahuozhong = false;
                this.fahuowancheng = false;
                this.dangqianfahuo = 0;
                this.chenggongshu = 0;
                this.shibaishu = 0;
            },


            shezhidayin() {
                var url = "../print/main";
                mpvue.navigateTo({url})
            },

            shezhimidandan() {
                var url = "../addelecsheet/main?type=0";
                mpvue.navigateTo({url})
            },

            loadData() {
                this.loadRen();
                this.loadDayinji();
                this.loadMiandan();
            },
            // 弹窗确定
            doCancleDel() {
                this.$refs.tanchuanDel.hidden();
            },
            loadRen() {
                var _this = this;
                wx.request({
                    url:
                        wx.getStorageSync("otherPath") + api.queryShipperAddress +
                        "?ecstoken=" +
                        wx.getStorageSync("sessionId"),
                    data: {},
                    header: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                        ecstoken : wx.getStorageSync('sessionId'),
                        fslb : wx.getStorageSync('fslb')
                    },
                    method: "POST",
                    success(res) {
                        res.data.data.forEach((data,index) => {
                            _this.fajianrenNameList.push(data.contact);
                            _this.fajianrenList.push(data);
                            if(data.defaultFlag ==  "1"){
                                _this.fajianrenName = data.contact;
                                _this.fajianrenIndex = index.toString();
                            }
                        });
                    },
                    fail() {
                        _this.$refs.mytoast.show("网络异常");
                    }
                });
            },
            loadDayinji() {
                var _this = this;
                wx.request({
                    url: wx.getStorageSync("otherPath") + api.printerList + "?ecstoken=" + wx.getStorageSync("sessionId"),
                    method: "POST",
                    header: {
                        ecstoken : wx.getStorageSync('sessionId'),
                        fslb : wx.getStorageSync('fslb')
                    },
                    data: {},
                    success(res) {
                        res.data.data.forEach(data => {
                            _this.dayinjiNameList.push(data.aliasName);
                            _this.dayinjiList.push(data);

                        });
                    },
                    fail() {
                        _this.$refs.mytoast.show("网络异常");
                    }
                });
            },
            loadMiandan() {
                var _this = this;
                wx.request({
                    url:
                        wx.getStorageSync("otherPath") + api.queryAllUserWaybillTemplateWithAttr +
                        "?ecstoken=" +
                        wx.getStorageSync("sessionId"),
                    method: "POST",
                    header: {
                        ecstoken : wx.getStorageSync('sessionId'),
                        fslb : wx.getStorageSync('fslb')
                    },
                    data: {},
                    success(res) {
                        res.data.data.forEach(data => {
                            _this.miandanNameList.push(data.aliases);
                            _this.miandanList.push(data);
                        });
                    },
                    fail() {
                        _this.$refs.mytoast.show("网络异常");
                    }
                });
            },
            bindfajianrenchange(e) {
                var index = e.mp.detail.value;
                this.fajianrenIndex = index;
                this.fajianrenName = this.fajianrenNameList[index];
            },
            bindDayinjichange(e) {
                var index = e.mp.detail.value;
                this.dayinjiIndex = index;
                this.dayinjiName = this.dayinjiNameList[index];
            },
            bindMiandanchange(e) {
                var index = e.mp.detail.value;
                this.miandanIndex = index;
                this.miandanName = this.miandanNameList[index];
            },
            // 打印快递单
            printOrder() {
                var _this = this;
                if(check.isNull(this.fajianrenIndex)){
                    this.$refs.mytoast.show("请选择发件人");
                    return;
                }
                if(check.isNull(this.dayinjiIndex)){
                    this.$refs.mytoast.show("请选择打印机");
                    return;
                }
                if(check.isNull(this.miandanIndex)){
                    this.$refs.mytoast.show("请选择电子面单");
                    return;
                }
                _this.doConfirm();
                _this.dayinflag = true;
                _this.fahuozhong = true;
                for(var i = 0 ; i <  _this.orderNolist.length ; i ++){
                    wx.request({
                        url: wx.getStorageSync("otherPath") + api.checkAndPrint + "?ecstoken=" + wx.getStorageSync('sessionId'),
                        method: "POST",
                        header: {
                            'Content-Type': 'application/x-www-form-urlencoded',
                            ecstoken : wx.getStorageSync('sessionId'),
                            fslb : wx.getStorageSync('fslb')
                        },
                        data: {
                            orderNo: _this.orderNolist[i], //JSON.stringify()
                            addressId: _this.fajianrenList[_this.fajianrenIndex].id,
                            printerId: _this.dayinjiList[_this.dayinjiIndex].id,
                            userTemplateId: _this.miandanList[_this.miandanIndex].id,
                        },
                        success(res) {
                            _this.dangqianfahuo ++;
                            console.log("正在打印第"+_this.dangqianfahuo+"个订单")
                            //开始打印
                            console.log(res);
                            try {
                                if (res.data.data.hasOwnProperty("cmds")) {
                                    console.log((i + 1) + "打印成功")
                                    //_this.msg = ;
                                    _this.openBluetoothAdapter(res.data.data.orderNo, res.data.data.cmds);

                                } else if (res.data.data.hasOwnProperty("errorMsg")) {
                                    console.log((i + 1) + "打印失败")
                                    _this.shibaishu++;
                                    var obj = {
                                        orderNo: res.data.data.orderNo,
                                        msg: res.data.data.errorMsg
                                    }
                                    _this.fahuoList.push(obj);
                                }
                            }catch (e) {
                                console.log((i + 1) + "打印失败")
                                _this.shibaishu++;
                                /*
                                var obj = {
                                    orderNo: res.data.data.orderNo,
                                    msg: res.data.data.msg
                                }
                                _this.fahuoList.push(obj);*/
                            }
                            if(_this.dangqianfahuo == _this.orderNolist.length){
                                _this.fahuozhong = false;
                                _this.fahuowancheng = true;
                                console.log("打印完成，显示完成界面")
                            }
                        },
                        fail() {
                            _this.dangqianfahuo ++;
                            console.log("正在打印第"+_this.dangqianfahuo+"个订单")
                            _this.$refs.mytoast.show('网络异常');
                            if(_this.dangqianfahuo == _this.orderNolist.length){
                                _this.fahuozhong = false;
                                _this.fahuowancheng = true;
                                console.log("打印完成，显示完成界面")
                            }
                        },
                    })
                }
            },

            //获取蓝牙设备状态
            openBluetoothAdapter(orderNo,msg) {
                var _this = this;
                wx.openBluetoothAdapter({
                    success: res => {
                        console.log("openBluetoothAdapter success", res);
                        _this.startBluetoothDevicesDiscovery(orderNo,msg);
                    },
                    fail: res => {
                        var obj = {
                            orderNo: orderNo,
                            msg: ''
                        }
                        _this.fahuoList.push(obj);
                        if (res.errCode === 10001) {
                            _this.$refs.mytoast.show("请打开蓝牙");
                            /*
                            wx.onBluetoothAdapterStateChange(function (res) {
                                console.log("onBluetoothAdapterStateChange", res);
                                if (res.available) {
                                    _this.startBluetoothDevicesDiscovery(orderNo,msg);
                                }
                            });*/
                        }
                    }
                });
            },

            //发现设备
            startBluetoothDevicesDiscovery(orderNo,msg) {
                var _this = this;
                _this.createBLEConnection(_this.dayinjiList[_this.dayinjiIndex].deviceId,orderNo,msg);
                /*  wx.startBluetoothDevicesDiscovery({
                      allowDuplicatesKey: true,
                      success: res => {
                          console.log("startBluetoothDevicesDiscovery success", res);
                          _this.onBluetoothDeviceFound();
                      }
                  });*/
            },

            //发下设备
            onBluetoothDeviceFound() {
                var _this = this;
                wx.onBluetoothDeviceFound(res => {
                    res.devices.forEach(device => {
                        if (device.deviceId == _this.deviceId) {
                            _this.createBLEConnection(device.deviceId);
                        }
                    });
                });
            },


            //创建链接
            createBLEConnection(deviceId,orderNo,msg) {
                var _this = this;
                wx.createBLEConnection({
                    deviceId,
                    success: res => {
                        console.log(res);
                        _this.getBLEDeviceServices(deviceId,orderNo,msg);
                    },
                    fail: res => {
                        _this.$refs.mytoast.show("未发现设备");
                        var obj = {
                            orderNo: orderNo,
                            msg: ''
                        }
                        _this.fahuoList.push(obj);
                    }
                });
                this.stopBluetoothDevicesDiscovery();
            },
            //获取设备
            getBLEDeviceServices(deviceId,orderNo,msg) {
                var _this = this;
                wx.getBLEDeviceServices({
                    deviceId,
                    success: res => {
                        for (let i = 0; i < res.services.length; i++) {
                            if (res.services[i].isPrimary) {
                                this.getBLEDeviceCharacteristics(deviceId, res.services[i].uuid,orderNo,msg);
                                //return;
                            }
                        }
                    },
                    fail : res=>{
                        var obj = {
                            orderNo: orderNo,
                            msg: ''
                        }
                        _this.fahuoList.push(obj);
                    }
                });
            },

            getBLEDeviceCharacteristics(deviceId, serviceId,orderNo,msg) {
                var _this = this;
                wx.getBLEDeviceCharacteristics({
                    deviceId,
                    serviceId,
                    success: res => {
                        console.log(
                            "getBLEDeviceCharacteristics success",
                            res.characteristics
                        );
                        for (let i = 0; i < res.characteristics.length; i++) {
                            let item = res.characteristics[i];
                            if (item.properties.read) {
                                wx.readBLECharacteristicValue({
                                    deviceId,
                                    serviceId,
                                    characteristicId: item.uuid,
                                    success(res) {
                                        console.log('readBLECharacteristicValue:', res.errCode)
                                    }
                                });
                            }
                            if (item.properties.write) {
                                _this._deviceId = deviceId;
                                _this._serviceId = serviceId;
                                _this._characteristicId = item.uuid;
                                _this.writeBLECharacteristicValue(orderNo,msg);
                                break;
                            }
                            if (item.properties.notify || item.properties.indicate) {
                                wx.notifyBLECharacteristicValueChange({
                                    deviceId,
                                    serviceId,
                                    characteristicId: item.uuid,
                                    state: true
                                });
                            }
                        }
                    },
                    fail(res) {
                        console.error("getBLEDeviceCharacteristics", res);
                        var obj = {
                            orderNo: orderNo,
                            msg: ''
                        }
                        _this.fahuoList.push(obj);
                    }
                });
                // 操作之前先监听，保证第一时间获取数据
                wx.onBLECharacteristicValueChange(res => {
                    console.log(`characteristic ${res.characteristicId} has changed, now is ${res.value}`)
                    console.log(_this.ab2hex(res.value))
                });
            },
            // ArrayBuffer转16进度字符串示例
            ab2hex(buffer) {
                var hexArr = Array.prototype.map.call(new Uint8Array(buffer), function (
                    bit
                ) {
                    return ("00" + bit.toString(16)).slice(-2);
                });
                return hexArr.join("");
            },
            writeBLECharacteristicValue(orderNo,msg) {
                var _this = this;
                // 向蓝牙设备发送16进制数据
                console.log("正式打印 orderNo : orderNo ;" + msg)
                var buffer = this.str2abnew(msg);
                wx.writeBLECharacteristicValue({
                    deviceId: this._deviceId,
                    serviceId: this._serviceId,
                    characteristicId: this._characteristicId,
                    value: buffer,
                    success(res) {
                        _this.chenggongshu++;
                        console.log('writeBLECharacteristicValue success', res.errMsg)
                    },
                    fail(res) {
                        var obj = {
                            orderNo: orderNo,
                            msg: ''
                        }
                        _this.fahuoList.push(obj);
                    }
                });
            },
            closeBluetoothAdapter() {
                wx.closeBluetoothAdapter();
            },
            //停止
            stopBluetoothDevicesDiscovery() {
                wx.stopBluetoothDevicesDiscovery();
            },
            str2abnew: function (str) {
                var typedArray = new Uint8Array(str.match(/[\da-f]{2}/gi).map(function (h) {
                    return parseInt(h, 16)
                }))
                var buffer = typedArray.buffer;
                return buffer;
            },
        }
    };
</script>

<style lang="wxss">
  page {
    width: 100%;
    height: 100%;
    background-color: #f7fbff;
  }
</style>

<style scoped>
  .addren-main {
    padding: 0 0.3rem;
    background-color: #ffffff;
    box-shadow: 0px 2px 4px 0px rgba(7, 127, 255, 0.1);
    color: #373e4f;
    font-size: 0.26rem;
    font-family: PingFang SC;
    font-weight: 500;
  }

  .list-itme {
    height: 40px;
    line-height: 40px;
    background-color: #ffffff;
    border-bottom: 0.5px solid #e8eaf0;
  }

  .list-itme span {
    font-size: 0.26rem;
  }

  .list-itme input {
    width: 75%;
    float: right;
    margin-top: 10px;
  }

  .placeholder {
    font-family: PingFang SC;
  }

  input::-webkit-input-placeholder,
  textarea::-webkit-input-placeholder {
    color: #a3aab7;
  }

  .no-data {
    color: #a3aab7;
    width: 100%;
    height: 40px;
    text-align: center;
    font-size: 0.24rem;
    line-height: 40px;
  }

  .add-ren-ft {
    width: 5%;
    float: right;
    content: " ";
    display: inline-block;
    height: 8px;
    width: 8px;
    border-width: 2px 2px 0 0;
    border-color: #b2b2b2;
    border-style: solid;
    -webkit-transform: matrix(0.71, 0.71, -0.71, 0.71, 0, 0);
    transform: matrix(0.71, 0.71, -0.71, 0.71, 0, 0);
  }

  .caozuo {
    height: 0.65rem;
    line-height: 0.65rem;
  }

  .caozuo a {
    height: 0.65rem;
    line-height: 0.65rem;
    float: right;
    font-size: 12px;
    font-family: PingFang SC;
    font-weight: 500;
    color: rgba(0, 119, 255, 1);
    margin-left: 12px;
  }

  .foot {
    border-top: 1px solid rgba(236, 239, 246, 1);
    text-align: center;
    vertical-align: middle;
    width: 100%;
    height: 40px;
    position: fixed;
    left: 0;
    bottom: 0;
    font-size: 15px;
    font-family: PingFang SC;
    font-weight: 500;
    line-height: 40px;
    display: flex;
    justify-content: space-around;
  }

  .foot .cancle {
    width: 50%;
    background-color: #ffffff;
  }

  .foot .queding {
    width: 50%;
    background-color: #0077ff;
  }

  .addren-foot {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 40px;
    background: #ff8900;
    text-align: center;
    color: #fff;
    font-size: 15px;
    line-height: 40px;
    font-weight: 500;
  }
</style>
